
package com.small.sentinel.slots.flow;

import com.small.common.core.spi.Spi;
import com.small.common.designPattern.behavioral.chainOfResponsibility.slotchain.AbstractLinkedProcessorSlot;
import com.small.sentinel.Constants;
import com.small.sentinel.slots.SentinelResource;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

@Spi(order = Constants.ORDER_FLOW_SLOT)
public class FlowSlot extends AbstractLinkedProcessorSlot<SentinelResource> {

    private FlowRuleChecker flowRuleChecker;

    public FlowSlot() {
        this.flowRuleChecker = new FlowRuleChecker();
    }

    @Override
    public void entry(SentinelResource resource) throws Throwable {
        flowRuleChecker.checkFlow(ruleProvider,resource);
        fireEntry(resource);
    }

    @Override
    public void exit(SentinelResource resource) throws Throwable {

    }


    private final Function<String, Collection<FlowRule>> ruleProvider = new Function<String, Collection<FlowRule>>() {
        @Override
        public Collection<FlowRule> apply(String resource) {
            // Flow rule map should not be null.
            Map<String, List<FlowRule>> flowRules = FlowRuleManager.getFlowRuleMap();
            return flowRules.get(resource);
        }
    };
}
